<template>
  <div class="admin-login-test-container">
    <div class="test-card">
      <h2>🔐 管理员登录功能测试</h2>
      
      <div class="test-section">
        <h3>1. 管理员登录测试</h3>
        <p>测试管理员登录功能是否正常</p>
        <el-form :model="adminForm" label-width="100px">
          <el-form-item label="管理员账号">
            <el-input v-model="adminForm.username" placeholder="请输入管理员账号" />
          </el-form-item>
          <el-form-item label="管理员密码">
            <el-input v-model="adminForm.password" type="password" placeholder="请输入管理员密码" />
          </el-form-item>
          <el-form-item>
            <el-button @click="testAdminLogin" :loading="loading.login" type="primary">测试登录</el-button>
          </el-form-item>
        </el-form>
        <p class="result">{{ results.login }}</p>
      </div>

      <div class="test-section">
        <h3>2. 管理员Token验证</h3>
        <p>测试管理员Token是否正确保存和获取</p>
        <el-button @click="testAdminToken" type="primary">测试Token</el-button>
        <p class="result">{{ results.token }}</p>
      </div>

      <div class="test-section">
        <h3>3. 管理员权限测试</h3>
        <p>测试管理员权限验证</p>
        <el-button @click="testAdminPermission" type="primary">测试权限</el-button>
        <p class="result">{{ results.permission }}</p>
      </div>

      <div class="test-section">
        <h3>4. 管理员API调用测试</h3>
        <p>测试管理员API是否可以正常调用</p>
        <el-button @click="testAdminAPI" type="primary">测试API调用</el-button>
        <p class="result">{{ results.api }}</p>
      </div>

      <div class="test-section">
        <h3>5. 管理员登出测试</h3>
        <p>测试管理员登出功能</p>
        <el-button @click="testAdminLogout" type="warning">测试登出</el-button>
        <p class="result">{{ results.logout }}</p>
      </div>

      <div class="test-section">
        <h3>6. 页面跳转测试</h3>
        <p>测试管理员页面跳转</p>
        <el-button @click="goToAdminLogin" type="info">跳转到管理员登录</el-button>
        <el-button @click="goToAdminDashboard" type="success">跳转到管理员仪表盘</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { adminLogin } from '@/utils/apiService'
import { 
  saveAdminToken, 
  getAdminToken, 
  saveAdminInfo, 
  getAdminInfo, 
  isAdminLoggedIn, 
  adminLogout,
  hasPermission 
} from '@/utils/auth'
import api from '@/utils/api'

const router = useRouter()

// 加载状态
const loading = reactive({
  login: false
})

// 测试结果
const results = reactive({
  login: '',
  token: '',
  permission: '',
  api: '',
  logout: ''
})

// 管理员表单
const adminForm = reactive({
  username: 'admin',
  password: 'admin123'
})

// 1. 测试管理员登录
const testAdminLogin = async () => {
  loading.login = true
  try {
    const response = await adminLogin({
      username: adminForm.username,
      password: adminForm.password
    })

    if (response.data.code === "200" || response.data.code === 200) {
      // 保存token和管理员信息
      if (response.data.data.info) {
        saveAdminToken(response.data.data.info)
      }

      if (response.data.data.loginAdmin) {
        saveAdminInfo(response.data.data.loginAdmin)
      }

      results.login = `✅ 登录成功: Token=${response.data.data.info?.substring(0, 20)}...`
      ElMessage.success('管理员登录成功')
    } else {
      results.login = `❌ 登录失败: ${response.data.message}`
      ElMessage.error('管理员登录失败')
    }
  } catch (error) {
    results.login = `❌ 登录异常: ${error.response?.data?.message || error.message}`
    ElMessage.error('管理员登录异常')
  } finally {
    loading.login = false
  }
}

// 2. 测试管理员Token
const testAdminToken = () => {
  try {
    const token = getAdminToken()
    const adminInfo = getAdminInfo()
    const isLoggedIn = isAdminLoggedIn()

    results.token = `✅ Token状态:
Token: ${token ? token.substring(0, 20) + '...' : '无'}
管理员信息: ${adminInfo ? JSON.stringify(adminInfo, null, 2) : '无'}
登录状态: ${isLoggedIn ? '已登录' : '未登录'}`

    ElMessage.success('Token验证完成')
  } catch (error) {
    results.token = `❌ Token验证失败: ${error.message}`
    ElMessage.error('Token验证失败')
  }
}

// 3. 测试管理员权限
const testAdminPermission = () => {
  try {
    const hasAdminPermission = hasPermission('admin')
    const hasUserPermission = hasPermission('user')

    results.permission = `✅ 权限验证结果:
管理员权限: ${hasAdminPermission ? '有' : '无'}
用户权限: ${hasUserPermission ? '有' : '无'}`

    ElMessage.success('权限验证完成')
  } catch (error) {
    results.permission = `❌ 权限验证失败: ${error.message}`
    ElMessage.error('权限验证失败')
  }
}

// 4. 测试管理员API调用
const testAdminAPI = async () => {
  try {
    const token = getAdminToken()
    if (!token) {
      results.api = `❌ 请先登录管理员账号`
      ElMessage.warning('请先登录管理员账号')
      return
    }

    // 测试调用管理员API
    const response = await api.get('/admin/agent/list', {
      headers: {
        'info': token
      }
    })

    if (response.data.code === "200" || response.data.code === 200) {
      results.api = `✅ API调用成功: 获取到 ${response.data.data?.length || 0} 条中介申请记录`
      ElMessage.success('管理员API调用成功')
    } else {
      results.api = `❌ API调用失败: ${response.data.message}`
      ElMessage.error('管理员API调用失败')
    }
  } catch (error) {
    results.api = `❌ API调用异常: ${error.response?.data?.message || error.message}`
    ElMessage.error('管理员API调用异常')
  }
}

// 5. 测试管理员登出
const testAdminLogout = async () => {
  try {
    await adminLogout()
    results.logout = `✅ 登出成功，本地存储已清除`
    ElMessage.success('管理员登出成功')
  } catch (error) {
    results.logout = `❌ 登出失败: ${error.message}`
    ElMessage.error('管理员登出失败')
  }
}

// 6. 页面跳转
const goToAdminLogin = () => {
  router.push('/admin-login')
}

const goToAdminDashboard = () => {
  router.push('/admin/dashboard')
}
</script>

<style scoped>
.admin-login-test-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.test-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.test-card h2 {
  color: #2c3e50;
  margin-bottom: 30px;
  text-align: center;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e1e8ed;
  border-radius: 8px;
  background: #f8f9fa;
}

.test-section h3 {
  margin-top: 0;
  color: #34495e;
  margin-bottom: 10px;
}

.test-section p {
  color: #7f8c8d;
  margin-bottom: 15px;
}

.result {
  margin-top: 15px;
  padding: 15px;
  background: #ffffff;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
  border-left: 4px solid #3498db;
  max-height: 200px;
  overflow-y: auto;
}

.el-button {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
